package com.hex.liyue.usermodule.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hex.liyue.R;
import com.hex.liyue.commonmodule.fragment.BaseFragment;
import com.hex.liyue.commonmodule.glide.GlideRoundTransform;
import com.hex.liyue.commonmodule.utils.FileUtis;
import com.hex.liyue.commonmodule.utils.ImageUtils;
import com.hex.liyue.commonmodule.view.DelayButton;
import com.hex.liyue.mainmodule.activity.MainActivity;
import com.hex.liyue.usermodule.presenter.IRegistVIew;
import com.hex.liyue.usermodule.presenter.RegistPresenter;
import com.hex.liyue.usermodule.view.PhotoSelectDialog;

import java.io.File;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * 这是一个注册界面
 * Created by yukoyuan on 16/6/14.
 */
public class RegistFragment extends BaseFragment implements IRegistVIew, DelayButton.OnDelayListener, TextWatcher {
    @Bind(R.id.et_regist_name)
    EditText etRegistName;
    @Bind(R.id.et_regist_phone)
    EditText etRegistPhone;
    @Bind(R.id.et_regist_vcode)
    EditText etRegistVcode;
    @Bind(R.id.db_getvcode)
    DelayButton dbGetvcode;
    @Bind(R.id.et_regist_pwd)
    EditText etRegistPwd;
    @Bind(R.id.iv_toobar_back)
    ImageView ivToobarBack;
    @Bind(R.id.iv_pwd)
    ImageView ivPwd;
    @Bind(R.id.iv_regist_edit_avator)
    ImageView ivRegistEditAvator;
    @Bind(R.id.tv_toobar_title)
    TextView tvToobarTitle;
    @Bind(R.id.bt_regist)
    TextView btRegist;
    private File avatorfile; //刚上传的图片路径
    private RegistPresenter registPresenter;
    private boolean flagNow = true;
    private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 裁剪结果
    private static final int RESULT_OK = -1;
    private PhotoSelectDialog photoSelectDialog;//头像对话框
    private File photoFile;

    @Override
    public void initdata(Bundle arguments) {
        etRegistName.addTextChangedListener(this);
        etRegistPhone.addTextChangedListener(this);
        etRegistPwd.addTextChangedListener(this);
        etRegistVcode.addTextChangedListener(this);
        dbGetvcode.setDelayListener(this);
    }

    @Override
    public int getContentLayout() {
        return R.layout.fragment_regist;
    }

    @Override
    protected void bindPresenter() {
        registPresenter = new RegistPresenter(this);
    }

    @Override
    protected void initToolbar() {
        ivToobarBack.setVisibility(View.VISIBLE);
        tvToobarTitle.setVisibility(View.VISIBLE);
        tvToobarTitle.setText("注册");
    }

    @Override
    public File getAvatar() {
        return avatorfile;
    }

    @Override
    public String getVcode() {
        return etRegistVcode.getText().toString().trim();
    }

    @Override
    public String getPhone() {
        return etRegistPhone.getText().toString().trim();
    }

    @Override
    public String getUserName() {
        return etRegistName.getText().toString().trim();
    }


    @Override
    public String getPwd() {
        return etRegistPwd.getText().toString().trim();
    }

    @Override
    public void showLod(String msg) {
        showLoad(getActivity(), msg);
    }

    @Override
    public void closeLod() {
        closeLoad();
    }

    @Override
    public void showT(String msg) {
        showToast(getActivity(), msg);
    }

    @Override
    public void gotoLoginFragment() {
        getActivity().onBackPressed();
    }

    @Override
    public void delyTime(int time) {
        dbGetvcode.delay(time);
    }

    @Override
    public void startMainActivity() {
        Intent intent = new Intent(getActivity(), MainActivity.class);
        getActivity().startActivity(intent);
        getActivity().finish();
    }


    @OnClick({R.id.db_getvcode, R.id.bt_regist, R.id.tv_regist_goto_login, R.id.iv_toobar_back, R.id.iv_pwd, R.id.iv_regist_edit_avator})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.db_getvcode:
                registPresenter.getVcode();
                break;
            case R.id.bt_regist:
                registPresenter.regist();
                break;
            case R.id.tv_regist_goto_login:
                gotoLoginFragment();
                break;
            case R.id.iv_toobar_back:
                gotoLoginFragment();
                break;
            case R.id.iv_regist_edit_avator://设置头像
                showPhotoDialog();
                break;
            case R.id.iv_pwd:
                if (flagNow) {
                    etRegistPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    flagNow = false;
                    ivPwd.setBackgroundResource(R.drawable.show_password);
                } else {
                    //否则隐藏密码
                    etRegistPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    flagNow = true;
                    ivPwd.setBackgroundResource(R.drawable.no_show_password);
                }
                break;
        }
    }

    /**
     * 启动裁剪图片功能
     *
     * @param uri
     * @param size
     */
    private void startPhotoZoom(Uri uri, int size) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 4);
        intent.putExtra("aspectY", 3);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 400);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }


    /**
     * Activity回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_TAKEPHOTO && resultCode == RESULT_OK) {
            startPhotoZoom(Uri.fromFile(photoFile), 200);
        } else if (requestCode == PHOTO_REQUEST_GALLERY && resultCode == RESULT_OK) {
            if (data != null) {
                startPhotoZoom(data.getData(), 200);
            }
        } else if (requestCode == PHOTO_REQUEST_CUT && resultCode == RESULT_OK) {
            if (data != null) {
                setPicToView(data);
            }
        }

    }

    /**
     * 获得截取后的照片
     *
     * @param data
     */
    private void setPicToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            File file = ImageUtils.saveBitmapFile(photo);
            if (extras != null) {
                Glide.with(this)
                        .load(file)
                        .error(R.drawable.setting_icon)
                        .transform(new GlideRoundTransform(getActivity()))
                        .into(ivRegistEditAvator);
                avatorfile = file;
            }
        }

    }

    /**
     * 显示头像对话框
     */
    private void showPhotoDialog() {
        if (photoSelectDialog == null) {
            photoSelectDialog = new PhotoSelectDialog(getActivity());
            photoSelectDialog.setOnPhotoListener(new PhotoSelectDialog.OnPhotoListener() {
                @Override
                public void photo() {
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            "image/*");
                    startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
                }

                @Override
                public void camera() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    String cameraPath = "/liyue/userphoto.jpg";
                    FileUtis.createDir();
                    photoFile = new File(Environment.getExternalStorageDirectory(), cameraPath);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                    startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                }

                @Override
                public void cancel() {
                    photoSelectDialog.dismiss();
                }
            });
        }
        photoSelectDialog.show();
    }

    @Override
    public void onStartDelay(int second) {
        dbGetvcode.setEnabled(false);
    }

    @Override
    public void onRun(int second) {

    }

    @Override
    public void onFinish() {
        if (dbGetvcode != null) {
            dbGetvcode.setEnabled(true);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if ((TextUtils.isEmpty(getVcode())) && (TextUtils.isEmpty(getPhone())) && (TextUtils.isEmpty(getUserName())) && (TextUtils.isEmpty(getPwd()))) {
            btRegist.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.bg_gray_broken));
        } else {
            btRegist.setBackgroundDrawable(getActivity().getResources().getDrawable(R.drawable.bg_gray_yellow_broken));
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    @Override
    public void onResume() {
        super.onResume();
        etRegistName.addTextChangedListener(this);
        etRegistPhone.addTextChangedListener(this);
//        etRegistInvitecode.addTextChangedListener(this);
        etRegistPwd.addTextChangedListener(this);
        etRegistVcode.addTextChangedListener(this);
        dbGetvcode.setDelayListener(this);
    }
}
